<template>
	<view>
		<view class="flex align-center justify-center" style="height: 30vh;">
			<text class="h1 font-weight-bold">身份绑定</text>
		</view>
		<view class="flex flex-column mx-5">
			<!-- 手机号 -->
			<view class="flex border-bottom align-center" style="height: 100rpx;">
				<uni-icons class="mr-2 flex-shrink" fontFamily="iconfont" color="#bbcbd8" size="30">{{'\ue601'}}</uni-icons>
				<input class="w-100 font-sm" placeholder-class="font-sm" v-model="form.Member_SerialNumber" placeholder="请输入您的手机号" type="number"/>
			</view>
			<!-- 密码 -->
			<view class="flex mt-2 mb-5 align-center" style="height: 100rpx;">
				<view class="border-bottom w-100 flex align-center" style="height: 100rpx;">
					<uni-icons class="mr-2 flex-shrink" fontFamily="iconfont" color="#bbcbd8" size="30">{{'\ue668'}}</uni-icons>
					<input class="w-100 font-sm" placeholder-class="font-sm" v-model="form.Code" placeholder="请输入验证码" type="number" />
				</view>
				<view @click="sendMessage" class="text-center ml-2 flex-shrink font-sm text-white" style="background-color: rgb(196, 169, 123); width: 250rpx; line-height: 100rpx;">
					{{timer?'剩余'+secend+'s':CodePrompt}}
				</view>
			</view>
			<!-- 登录 -->
			<view @click="Login" class="flex justify-center mt-5 align-center text-white font-sm" style="background-color: rgb(204, 45, 30); height: 100rpx;">绑定身份</view>
		</view>
	</view>
</template>

<script>
	import { mapState,mapMutations } from 'vuex';
	import Base64 from "base-64";
	import { validatemobile,generateCode } from '@/static/js/GeneralUtil.js'
	import { getCurrentTimestamp } from '@/static/js/DateUtil.js';
	import { getMemberPoint,generalSave,generalQueryBySQLSerialNumber,SendSms } from '@/api/generalBusiness.js'
	import { accAdd } from '@/static/js/GeneralUtil.js'
	export default {
		data() {
			return {
				form:{
					Member_SerialNumber:'',
					Code:'',	
				},
				RandomCode:'',
				expires_in:0,//过期时间
				CodePrompt:'获取验证码',
				timer: null,
				secend: 60,
				loading:false,
			}
		},
		computed: {
			...mapState(['Open_ID','Member']),
		},
		methods: {
			...mapMutations(['setMember']),
			async sendMessage() {//发送验证码
				if(validatemobile(this.form.Member_SerialNumber)&&!this.timer){	
					this.secend = 60;
					this.secend--;
					this.timer = setInterval(() => {
						if (this.secend == '01') {
							clearInterval(this.timer)
							this.timer = null;
							return
						}
						this.secend--
						if (this.secend < 10) {
							this.secend = '0' + this.secend
						}
					}, 1000)
					this.RandomCode = generateCode();
					const res = await SendSms({
						code:this.RandomCode,
						phone:this.form.Member_SerialNumber
					})
					if(res.statusCode==200){
						this.CodePrompt = '重新获取';
						this.expires_in = getCurrentTimestamp() + 300;
					}else{
						uni.showToast({
							title:"系统繁忙",
							icon:'none'
						})
					}
					// uniCloud.callFunction({
					// 	name: 'sendSms', //对应的云函数名
					// 	data: {
					// 		phone: this.form.Member_SerialNumber,
					// 		data: {
					// 			name: '验证码',
					// 			code: this.RandomCode, //随机生成的验证码，如123456
					// 			action: '绑定', //校验类型为
					// 			expMinute: '5', //短信的有效期，5分钟
					// 		}
					// 	}
					// }).then(res => {
					// 	if (res.success) {
					// 		this.CodePrompt = '重新获取';
					// 		this.expires_in = getCurrentTimestamp() + 300;
					// 	}
					// }).catch(msg => {
					// 	uni.showToast({
					// 		title:"系统繁忙",
					// 		icon:'none'
					// 	})
					// });
				}
			},
			async Login(){
				//1.判断验证码是否正确
				if(this.Member.Member_SerialNumber){
					uni.showToast({
						title:'已被绑定身份，无法再次绑定！',
						icon:'none',
					})
				} else {
					if(validatemobile(this.form.Member_SerialNumber)){
						if(!this.loading&&this.RandomCode==this.form.Code&&this.RandomCode&&this.expires_in > getCurrentTimestamp()){
							this.loading = true;
							try{
								const {business_member_account_info,business_member_cash_points,business_member_info} = await getMemberPoint({
									Data:JSON.stringify([{
										tableName: 'business_member_info',
										Condition: Base64.encode(`Member_SerialNumber='${this.form.Member_SerialNumber}'`),
									},{
										tableName: 'business_member_cash_points',
										Condition: Base64.encode(`Member_SerialNumber='${this.form.Member_SerialNumber}'`)
									},{
										tableName: 'business_member_account_info',
										Condition: Base64.encode(`Open_ID='${this.Open_ID}'`)
									}])
								})
								if(business_member_info.length == 1){
									if(business_member_info[0].Open_ID){
										uni.showToast({
											title:'当前手机号已被绑定，无法再次绑定！',
											icon:'none'
										})
									} else {
										business_member_info[0].Open_ID = this.Open_ID;
										let Modify = {business_member_info};
										if(business_member_cash_points.length > 0){//判断当前用户有无积分方案
											//合并积分等信息
											let Cash_Point = business_member_account_info[0].Cash_Point;
											let Cash_Point_Sales = business_member_account_info[0].Cash_Point_Sales;
											let Cash_Point_Balance = business_member_account_info[0].Cash_Point_Balance;
											//现金积分合并
											business_member_cash_points.forEach(item=>{
												Cash_Point = accAdd(Cash_Point,item.Total_Points);
												Cash_Point_Sales = accAdd(Cash_Point_Sales,item.Sales_Points);
												Cash_Point_Balance = accAdd(Cash_Point_Balance,item.Remain_Points);
											})
											business_member_account_info[0].Cash_Point = Cash_Point;
											business_member_account_info[0].Cash_Point_Sales = Cash_Point_Sales;
											business_member_account_info[0].Cash_Point_Balance = Cash_Point_Balance;
											Modify['business_member_account_info'] = business_member_account_info;
										}
										const res = await generalSave({Data:JSON.stringify({Modify})})
										if(res.Status=="success"){
											//更新用户信息
											let data = await generalQueryBySQLSerialNumber({
												SQLSerialNumber:'M_business_member_account_info',
												Condition:Base64.encode(this.Open_ID),
												ExtensionCondition:''
											})
											this.setMember(data[0]);
											uni.showModal({
												title: "提示",
												content: "是否完善个人信息",
												success: function(res) {
													if (res.confirm) {
														uni.navigateTo({url: "/pages/my/information",});
													}else{
														uni.navigateBack();
													}
												},
											});
										} else {
											uni.showToast({
												title:'系统繁忙！',
												icon:'none'
											})
										}
									}
								} else {
									uni.showToast({
										title:'当前手机号未查询到身份信息，可咨询相关管理员确认！',
										icon:'none'
									})
								}
							} catch(e) {
								uni.showToast({
									title:'系统繁忙！',
									icon:'none'
								})
							}
							this.loading = false;
						}else{
							uni.showToast({
								title:'验证码不正确或已过期（有效期5分钟）！',
								icon:'none'
							})
						}
					}
				}
			}
		}
	}
</script>

<style>

</style>
